<?php

require_once(APP.'libs'.DS.'util.php');
require_once(APP.'libs'.DS.'system_properties.php');
App::import('Vendor','/infolex/rest_wrapper');
class UserController extends AppController
{
	var $helpers = array('javascript');
	var $layout='';
	var $uses=array('User','Product','Timesplit_logs','Luck');
	var $components=array('Upload');

	var $friends = array() ;
	function load(){
	    //人人应用的入口
        $this->render('start');
	}
	/**
	 * 跳转此action 就可以进行登录。
	 *
	 */
	function goLoginIframe($type = 0, $pid = 0, $page = 0, $page_menu = 0) {
		if ($type!= 'details' && $type!= 'convertdetails') {
			$type = '0';
		}
		$pid = intval($pid);
		if (empty($page) ) {
			$page = '0';
		}
		if (empty($page_menu) ) {
			$page_menu = '0';
		}
		
		if(SystemProperties::$platform == "sina")
		{
			$appurl = SystemProperties::$app_url."user/sinaIframeCallback/{$type}/{$pid}/{$page}/{$page_menu}";
			$o = new WeiboOAuth( WB_AKEY , WB_SKEY  );
			$keys = $o->getRequestToken();
			$aurl = $o->getAuthorizeURL( $keys['oauth_token'] ,false , $appurl);
			$_SESSION['xn_user_id'] = 0;
			$_SESSION['xn_sig_user'] = 0;
		}
		else if(SystemProperties::$platform == "qq")
		{
			$appurl = SystemProperties::$app_url."user/qqIframeCallback/{$type}/{$pid}/{$page}/{$page_menu}";
			$o = new MBOpenTOAuth( WB_AKEY , WB_SKEY  );
			$keys = $o->getRequestToken($appurl);
			$aurl = $o->getAuthorizeURL( $keys['oauth_token'] ,false , '');
			$_SESSION['qq_sig_name'] = "";
		}

        $_SESSION['keys'] = $keys;
        $_SESSION['user_id'] = 0;
        
		header('Location: '.$aurl);
		exit();
	}
	function sinaIframeCallback ($type = 0, $pid = 0, $page = 0, $page_menu = 0){
		//处理回调
		if ($type!= 'details' && $type!= 'convertdetails') {
			$type = '';
		}
		$pid = intval($pid);
				
        if (!empty($_SESSION['keys']['oauth_token']) &&!empty($_SESSION['keys']['oauth_token_secret']) ) {
            //检查授权
            $o = @new WeiboOAuth( WB_AKEY , WB_SKEY , $_SESSION['keys']['oauth_token'] , $_SESSION['keys']['oauth_token_secret']  );
            $last_key = @$o->getAccessToken(  $_REQUEST['oauth_verifier'] ) ;
            $_SESSION['last_key'] = $last_key;
            if (empty($last_key['user_id'])) {
                error_log('Sina Login Failed'.json_encode($last_key));
                header('Location: '.SystemProperties::$app_url);
                exit();
            } else {
                $_SESSION['xn_sig_user'] = $last_key['user_id'];
                header('Location: '.SystemProperties::$app_url."?type={$type}&product_id={$pid}&page={$page}&page_menu={$page_menu}");
                exit();
            }
	    } 
	    exit() ;
	}	

	function qqIframeCallback ($type = 0, $pid = 0, $page = 0, $page_menu = 0){
		//处理回调
		if ($type!= 'details' && $type!= 'convertdetails') {
			$type = '';
		}
		$pid = intval($pid);
				
        if (!empty($_SESSION['keys']['oauth_token']) &&!empty($_SESSION['keys']['oauth_token_secret']) ) {
            //检查授权
            $o = @new MBOpenTOAuth( WB_AKEY , WB_SKEY , $_SESSION['keys']['oauth_token'] , $_SESSION['keys']['oauth_token_secret']  );
            $last_key = @$o->getAccessToken(  $_REQUEST['oauth_verifier'] ) ;
            $_SESSION['last_key'] = $last_key;
	        if (empty($last_key['name'])) {
                error_log('QQ Login Failed'.json_encode($last_key));
                header('Location: '.SystemProperties::$app_url);
                exit();
            } else {
                $_SESSION['qq_sig_name'] = $last_key['name'];
                header('Location: '.SystemProperties::$app_url."?type={$type}&product_id={$pid}&page={$page}&page_menu={$page_menu}");
                exit();
            }
	    } 
	    exit() ;
	}	

	// 首页列表
	function index()
	{
	    //登录预处理
        $ret = $this->startUpProcessUser();
        if (empty($_SESSION['user_id']) && SystemProperties::$platform!='sina' && SystemProperties::$platform!='qq') {
            //处理失败--》未登录
            return ;
        }        
        
	    $this->layout = 'try_layout';
		$curPage=1;
		$this->set("now",date('Y-m-d H:i:s'));
		$this->render('index');
		return;
	}

	function startUpdateUserInfo() {
	    $g_id = $_SESSION['user_id'];
	    $uid = $_SESSION['xn_user_id'];
	    $rest=new RestWrapper();
	    $userInfo=$rest->getAppUser($uid); // sina user info
	    $data=$this->User->getUserInfoByPlatformId($uid); // happyTry user info
		$this->User->updateUserDate($g_id,$userInfo,$data);
		$this->User->UpdateUserIP($g_id);
	}
	function goProfile($uid) {
	    $data = $this->User->getUserInfoById($uid);
	    $platform_uid = $data['g_uid'];
	    $url = SystemProperties::get_profile_url($platform_uid);
	    header('Location: '.$url);
	    exit();
	}
	
	function renrenProcessCat(){
		$uid = $_SESSION['xn_user_id'];
		if (SystemProperties::$platform=='renren') {
			if (!empty($_REQUEST['xn_sig_session_key'])) {
			    $_SESSION['xn_sig_session_key'] = $_REQUEST['xn_sig_session_key'];
			}

			$_SESSION['cutepig'] = 0;
    		$_SESSION['parterner'] = '';
			if (!empty($_REQUEST['extra'])){
				if (strtolower($_REQUEST['extra']) == '27beffd3bef370a9673920e42fd66d1b' ){
					$dx=$this->User->saveCutePigLog($uid);
				    $_SESSION['cutepig'] = 1;
				    $_SESSION['parterner'] = 'pig';
				}
			}

			$parterner = SystemProperties::$paterner_class;
			if (!empty($parterner[strtolower($_REQUEST['extra'])])){
			    $type = strtolower($_REQUEST['extra']);
			    $dx=$this->User->saveCutePigLog($uid, $type);
				$_SESSION['parterner'] = $type;
			}else {
			    $_SESSION['parterner'] = '';
			}		
		}	    
	}
	
	function logout(){
		$_SESSION['xn_sig_user'] = 0;
		$_SESSION['xn_user_id'] = 0;
		$_SESSION['xn_user_id'] = 0;

		session_start();
		session_destroy();
		if (SystemProperties::$platform=='sina') {
			$rest=new RestWrapper();
			$rest->logout();
		}
		
		header('Location: '.SystemProperties::$app_url);
		exit(); 
	}
	/**
	 * old loadgame
	 *
	 */
	function startUpProcessUser() {
	    //Check User Status
	    //此时应该已经是已登录状态
		$rest=new RestWrapper();
		if (SystemProperties::$platform =='sina') {
		    $uid = $uid_in_session = $_SESSION['xn_sig_user'];	//$rest->getLoggedInUser();
		}else if(SystemProperties::$platform =='qq'){
			$uid = $uid_in_session = $_SESSION['qq_sig_name'];				//qq不返回UID 而是返回name
		} else {
            $uid = $uid_in_session = $rest->getLoggedInUser();		    
		}

		if(!empty($uid)){
			
		    //renren 合作分类的专门处理
            if (SystemProperties::$platform=='renren') {		    
                $this->renrenProcessCat();
            }

			if(SystemProperties::$platform=='qq')
				$data=$this->User->getUserInfoByPlatformName($uid);
			else
				$data=$this->User->getUserInfoByPlatformId($uid);

			if(empty($data)){
    			$userInfo=$rest->getAppUser($uid);

				if (empty($userInfo)){
					error_log("CyLOG Empyt userinfo: $uid");
				} else {
					error_log("CyLOG Got userinfo: $uid, ".json_encode($userInfo));
				}

			    //首次进入
				//检查如果MySpace站外 则插入邀请记录。
				if (SystemProperties::$platform == 'myspace' && !empty($_REQUEST['invite_token'])){
					$token = $_REQUEST['invite_token'];
					$datax = $rest->checkInviteToken($token);
					if (!empty($datax['inviter_uid'])){
						$this->User->saveInviteLog($datax['inviter_uid'],$datax['invitee_uid']);
					}
				}
				//邀请链接
				if (!empty($_REQUEST['i'])){
                    $_REQUEST['i'] = intval($_REQUEST['i']);
                    if ($_REQUEST['i']!=$uid) {
					   $this->User->saveInviteLog($_REQUEST['i'],$uid);
                    }
				}
				$result=$this->User->createUser($userInfo);
				error_log("CyLOG Create user: ".json_encode($result));

				if(SystemProperties::$platform == 'qq')
					$data=$this->User->getUserInfoByPlatformName($uid);
				else
					$data=$this->User->getUserInfoByPlatformId($uid);
				error_log("CyLOG Get user: $uid, ".json_encode($data));

    			if (SystemProperties::$platform == 'sina') {
				    $r = $rest->addFollow(1866189800);
    			    //$rest->sendWeibo("我正在玩#开心赚宝#，首创公平的试用算法一定能让大家体验到免费试用的乐趣！新鲜好礼等你免费试用，同时更可以积累积分去换礼！快来看看吧！地址是：".SystemProperties::$app_url.'?i='.$_SESSION['xn_user_id'].'&t='.rand(0,100000));
    			    $rest->sendWeibo("我开始使用新浪微博【免费试用品派发】应用#开心赚宝#了，可以免费领取兰蔻、PRADA、BURBERRY、Crocs…的试用装哦 ".SystemProperties::$app_url.'?i='.$_SESSION['xn_user_id'].'&t='.rand(0,100000));
    			}
				if (SystemProperties::$platform == 'qq') {
					$rest->sendWeibo("我开始使用腾讯微博【免费试用品派发】应用#开心赚宝#了，可以免费领取兰蔻、PRADA、BURBERRY、Crocs…的试用装哦 ".SystemProperties::$app_url.'?i='.$_SESSION['xn_user_id'].'&t='.rand(0,100000));
				}
			} 
			
			//$data 已经重新准备好
			if(!empty($data)){
				$g_id=$data['g_id'];
				$_SESSION['user_id']=$g_id;
				$_SESSION['xn_user_id']=$uid;
				return true;
			} else {
				$msg = sprintf('CyLOG url: %s, uid: %s', $_SERVER['REQUEST_URI'], $uid);
				error_log($msg);
			    error_log("Login Error Fatal ! ");
			    echo 'Login Error';
			    exit();
			}
		}else{
		    return false;
		}	    
	}
	
	function myluck($tab = 1) {
	    $this->layout = '';
		if(empty($_SESSION['user_id'])){
			echo "请您重新打开应用！";
			exit;
		}
		$uid=$_SESSION['user_id'];	
		$tab = intval($tab);
		$user = $this->User->getUserInfoById($uid);
		$data = $this->Luck->getMyAllLuck($uid);
		$data_kuaidi = $this->Luck->getMyKuaidi($uid);
		//error_log(var_export($data_kuaidi,1));
		$this->set("user_id",$uid);
		$this->set("user",$user);
		$this->set("tab",$tab);
		$this->set("data",$data);
		$this->set("data_kuaidi",$data_kuaidi);
		$this->render('myluck');		
	}


	/* cy add, 2011-4-2 */
	function saveFillCaptchaInfo(){
		$this->layout = '';
		if(empty($_SESSION['user_id'])){
			echo '请您刷新页面后再次尝试。';
			exit();
		}

		$g_id=$_SESSION['user_id'];
		$xn_user_id=$_SESSION['xn_user_id'];

		$data_old=$this->User->getUserInfoById($g_id);
		if (empty($data_old)){
			echo '请您刷新页面后再次尝试。';
			exit();
		}
		
		if (empty($_POST['realname']) || empty($_POST['phone']) || empty($_POST['address']) || empty($_POST['zipcode'])
			|| empty($_POST['province']) || empty($_POST['city']) || empty($_POST['birthday'])){
			echo '您填写的信息不完整，请填写完整所有信息。';
			exit();
		}

		$birthday_time = strtotime($_POST['birthday']);
		if (!$birthday_time){
			echo '生日格式：1984-01-01';exit;
		}

		$phone = trim($_POST['phone']);
		if (preg_match('/^\d{5,}$/', $phone) <= 0){
			echo '手机号格式错误，请填写真实号码，纯数字'; exit;
		}

		foreach ($_POST as $k=>$v) {
		    $_POST[$k] = htmlspecialchars(strip_tags($v));
		}
		$ret = $this->Product->saveUinfoAndActive($_POST['code'], $_POST['realname'], $_POST['phone'], $_POST['birthday'], $_POST['address'], $_POST['zipcode'], $_POST['province'], $_POST['city'], 'active');
		if (!empty($_POST['from']) && $_POST['from']=='alert_daofu') {
		    echo '<script type="text/javascript">sendKuaidi("daofu");</script>';
		} else {
		    echo '<script type="text/javascript">showAlert("信息保存成功！");goMyluck(nowtab);</script>';
		}
        exit();
	}
	function showFillCaptchaInfo($captcha){

		$this->layout = '';

		if(empty($_SESSION['user_id'])){
			echo '请您刷新页面后再次尝试。';
			exit();
		}
		$g_id=$_SESSION['user_id'];
		$xn_user_id=$_SESSION['xn_user_id'];

		$g_id = intval($g_id);

		$data=$this->Product->getCaptchaUinfo($captcha, 'pre');
		if (empty($data) && !( $data=$this->Product->getCaptchaUinfo($captcha, 'active'))){
			echo '请您刷新页面后再次尝试。';
			exit();
		}
		if ($_SESSION['user_id'] != $data['user_id']){
			echo '请您刷新页面后再次尝试。';
			exit();
		}
		
		foreach ($data as $k=>$v){
			@$data[$k] = htmlspecialchars($v);
		}
		$this->set("data",$data);
		$this->render('fillinfo_captcha');
		return;

	}



	//填写信息
	function showFillInfo($type = 2){

		$this->layout = '';

		if(empty($_SESSION['user_id'])){
			echo '请您刷新页面后再次尝试。';
			exit();
		}
		$g_id=$_SESSION['user_id'];
		$xn_user_id=$_SESSION['xn_user_id'];

		$g_id = intval($g_id);

		$data=$this->User->getUserInfoById($g_id);//query("select * from g_users u where g_id={$g_id} limit 1");
		if (empty($data)){
			echo '请您刷新页面后再次尝试。';
			exit();
		}
		
		foreach ($data as $k=>$v){
			@$data[$k] = htmlspecialchars($v);
		}
		$this->set("data",$data);
		$this->set("type",$type);
		$this->render('fillinfo2');
		return;

	}

	//保存
	function saveFillInfo(){
		$this->layout = '';
		if(empty($_SESSION['user_id'])){
			echo '请您刷新页面后再次尝试。';
			exit();
		}

		$g_id=$_SESSION['user_id'];
		$xn_user_id=$_SESSION['xn_user_id'];

		$data_old=$this->User->getUserInfoById($g_id);
		if (empty($data_old)){
			echo '请您刷新页面后再次尝试。';
			exit();
		}
		
		if (strlen($_POST['idcard'])!=15 && strlen($_POST['idcard'])!=18) {
		    echo '您填写的身份证号码不正确，请正确填写。';
			exit();
		}
		if (empty($_POST['realname']) 
		//|| empty($_POST['birthday']) 
		|| empty($_POST['phone']) 
		|| empty($_POST['mail']) 
		|| empty($_POST['address'])
		|| empty($_POST['idcard'])
		|| empty($_POST['zipcode'])
		//|| (empty($_POST['kuaidi']) && SystemProperties::$platform!='yoka')
		//|| empty($_POST['interest'])
		){
			echo '您填写的信息不完整，请填写完整所有信息。';
			exit();
		}

		foreach ($_POST as $k=>$v) {
		    $_POST[$k] = htmlspecialchars(strip_tags($v));
		}
//		if ($_POST['sex']!=1){
//			$_POST['sex'] = 0;
//		}
//		$_POST['birthday'] = date('Y-m-d',strtotime($_POST['birthday']));
		$ret = $this->User->saveUserInfo($g_id,$_POST);
		if (!empty($_POST['from']) && $_POST['from']=='alert_daofu') {
		    echo '<script type="text/javascript">sendKuaidi("daofu");</script>';
		} else {
		    echo '<script type="text/javascript">showAlert("信息保存成功！");goMyluck(nowtab);</script>';
		}

//		if (empty($data_old['g_realname'])){
//			$sql = "update g_users set `g_canapply`=`g_canapply`+5 where `g_id`='{$g_id}'";
//			$this->User->query($sql);
//			echo '<script type="text/javascript">alert("信息保存成功！恭喜获得5次申请机会！");closeMessageBoxBase($("messageBoxCase"),1,"undefined")</script>';
//			exit();
//		}else {
//			echo '<script type="text/javascript">alert("信息保存成功！");closeMessageBoxBase($("messageBoxCase"),1,"undefined")</script>';
//			exit();
//		}
        exit();
	}
	// 取得用户信息
	function getUserInfo($uid = 0)
	{
	    $this->startUpdateUserInfo();
	    //if (empty($uid)) {
        $uid = $_SESSION['user_id'];
	    //}
	    $uid = intval($uid);
	    $data = $this->User->getUserInfoById($uid);
	    if (empty($data)) {
	        
	    } else {
	   		if (SystemProperties::$platform == 'myspace'){
				$data['g_head'] = str_replace('m_','c_',$data['g_head']);
			}
			$data['luck_count'] = $this->Luck->getLuckCount_WithCache($uid);
			$data['luck_unshare'] = $this->Luck->getUnShareCount_WithCache($uid);
	    }
	    $this->set("user", $data);
		$this->render('try_user_info');
	}


	function __getProductFreeList($curPage,$cat=0){
	    $focus = json_decode($this->User->getConfig('focus'), 1);
        $this->set("focus", $focus);
		if ($this->User->check_is_in_blacklist_WithCache($_SESSION['xn_user_id'])) {
		    $this->set("productFreeList",array());
			$this->set("curPage",0);
		    $this->set("totalPage",0);
		} else {	
    		if ($curPage<1) {
    		    $curPage = 1;
    		}
    		$number=SystemProperties::$product_pageNumber;
    		$start = ($curPage - 1) *$number;
		    $cat = intval($cat);
		    $total = 0;

    		$list = $this->Product->getProductFreeList($start,$number,$cat,$total);
    		$page = intval($total / $number)+1;
			$this->set("productFreeList",$list);
			$this->set("curPage",$curPage);
		    $this->set("totalPage",$page);
		}

		$this->set('product_stat',$this->Product->getStatic_WithCache('zhuan'));
		$this->set('product_cat',$cat);

	}





	/*
	* Desc： userd for try_product_detail.ctp
	* 点击 再看看吧 返回首页产品列表
	*/
	function productAllList(){
		$this->layout = '';
		if(isset($this->params['url']['curPage']) ){
			$this->__getProductList($curPage);
			$this->__getProductFreeList($curPage);
			$this->render('/product/try_product_list');
			return;
		}
	}

	// 免费产品列表
	function productFreeList($cat=0)
	{
		$this->layout = '';
		if(isset($this->params['url']['curPage']) ){
			$curPage=$this->params['url']['curPage'];
		}else{
			$curPage= 1;
		}
		$curPage = $curPage<1?1:intval($curPage);
		$this->__getProductFreeList($curPage, $cat);
		$this->set('pd_type','free');
		$this->render('/product/try_product_list');
		//$this->render('/product/try_product_free_list');
		return;
	}

	function sendInviteMessage() {
	    $text = $_GET['iv_ct'];
        $rest=new RestWrapper();
        $data = $rest->sendWeibo($text);
        echo '<script>showAlert("已经发送，谢谢！")</script>';
        exit();
	}

	// 显示邀请页面
	function showInvitationPage(){
	    
		$this->layout = '';
		$rest=new RestWrapper();
		$uid_in_session = $rest->getLoggedInUser();
		$uid = $this->User->getUserIdByPlatformUId($uid_in_session);
		$list = $this->User->select_invite_friends($uid_in_session);
		$this->set("list",$list);
		$this->render("show_invitation_page");
	}

	// 邀请好友
	function inviteFriends(){
		$rest=new RestWrapper();
		$uid = $rest->getLoggedInUser();
		$ids = $_REQUEST['ids'];
		if (SystemProperties::$platform == 'myspace'){
			$ids = empty($_REQUEST['friendids'])?'':trim($_REQUEST['friendids']);
			if (!empty($ids)){
				$ids = explode(',',$ids);
			}
		}
		if(!empty($uid)&&!empty($ids)){

			//记录邀请记录
			$g_ids=$rest->areFriends($uid,$ids);
			foreach ($g_ids as $to_id){
				$this->User->saveInviteLog($uid,$to_id);
			}

		}
		$this->layout = '';
		$this->render("show_invitation_done");

	}
	function ajaxListRecentApply() {
	    $recent_data = $this->User->getRecentApply(8);
	    $this->set("recent_data",$recent_data);
		$this->layout = '';
		$this->render("try_friends_list_recent_rec");	    	    
	}
	function ajaxListLuckUsers($p) {
	    $p = $p<1?1:intval($p);
	    $count = 9;
	    
	    $start = ($p-1) * $count;
        $recent_data = $this->Luck->listAllLuckUsers_WithCache($start, $count, $total);
	    $this->set("recent_data",$recent_data);
	    $this->set("total",$total);
	    $this->set("page",$p);
	    $this->set("totalp",intval($total/$count+1));
		$this->layout = '';
		$this->render("luck_users");	    	    
	}
	function ajaxSetLuckReceive($id, $type ,$kuaidi_type = '') {
	    
	    $uid=intval($_SESSION['user_id']);
	    if (empty($uid)){
	        return;
	    }
	    $id = explode(',',$id);
	    $type = ($type == 1)?'y':'n';
	    $update = array('is_get'=>$type);
	    if (!empty($kuaidi_type)) {
	        $update['kuaidi_type'] = $kuaidi_type;
	        $update['kuaidi_request_time'] = date('Y-m-d H:i:s');
	    }
	    
	    $this->Luck->updateLuck($uid, $id, $update);
	    exit();
	}
	
	function ajaxAddFollow() {
	    $rest=new RestWrapper();
	    $r = $rest->addFollow(1866189800);
	    echo '<script>showAlert("感谢您的关注！")</script>';
	    exit();
	}
	function ajaxAddFollowUid($uid) {
	    $rest=new RestWrapper();
	    $r = $rest->addFollow($uid);
	    echo '<script>alert("感谢您的关注！")</script>';
	    exit();
	    
	}
	function saveWhyNotGet() {
	    /**
	     *     [id] => 9
                [why_not_get] => 忘记领取
                [why_not_get_word] => 

	     */
        $uid=intval($_SESSION['user_id']);
	    if (empty($uid)){
	        return;
	    }	    
	    $id = $_POST['id'];
	    if (empty($_POST['id']) || empty($_POST['why_not_get'])) {
	        echo '<script>showAlert("请您选择一个原因。")</script>';
	        exit();
	    }
	    $word = $_POST['why_not_get'].$_POST['why_not_get_word'];
        $this->Luck->updateLuck($uid, $id, array('is_get'=>'n','why_not_get'=>$word));
        echo '<script>showAlert("提交成功，感谢您的支持。");goMyluck(nowtab);</script>';
	    exit();
	}
	function showSelectKuaidi() {
	?>
	<div class="mbBig" >
	<div class="mbInner">
	
	<div class="alerttitle">选择快递方式</div>
	<div style="padding:0px 50px;text-align:left;line-height:30px;">
	您有以下两种领取宝贝方式：<br />
	1.邮费货到付款<br />
	（北京到付10元，其他地区15元）<br /><br />
    2.自行联系快递<br /><br />
    </div>
    <div style="padding:0px 80px;overflow:hidden;zoom:1;">
    <a class="bta4" style="margin-right:20px;" href="javascript:showAlert('/user/showAlertSaveInfo','url')">货到付款</a>    
    <a class="bta4" style="margin-right:20px;" href="javascript:showAlert('/user/showSelectZiqu','url')">自行联系</a>    
    <a class="bta4g" href="javascript:Mediabox.close()">取消</a>
    </div>
    </div>
    </div>
    <?php 
        exit();
	}
	
	function showSelectZiqu() {
	?>
	
	<div class="mbBig">
	<div class="mbInner">
	<div class="alerttitle">自行联系快递取件</div>
	<table style="text-align:left">	
    <tr><td width="70">取件地址：</td><td>北京市朝阳区甜水园街万科公园5号9—1906</td></tr>
    <tr><td>邮   编：</td><td>100026</td></tr>
    <tr><td>联 系 人：</td><td>韩艳浇</td></tr>
    </table>
    <br />
    注：请在5个工作日内联系快递到开心赚宝自取宝贝，<br />
        并明确告诉取件快递员所领取的物品名称。<br />
    
    <br />
    <a class="bta4g fr" href="javascript:showSelectKuaidi()">取消</a>    
    <a class="bta4 fr" href="javascript:sendKuaidi('ziqu')">确认提交</a>    
        
    </div>
    </div>
	<?php 
	   exit();
	}
	
	function showAlertSaveInfo() {
	    $uid=$_SESSION['user_id'];
	    $user = $this->User->getUserInfoById($uid);
	?>
	<div class="mbBig">
	<div class="mbInner">
	       <div class="alerttitle" >确认快递信息</div>
            <form name='update_info' id="update_info_alert" method="POST" action="" style="line-height:32px;">
            <input type="hidden" name="from" value="alert_daofu" />
            <table cellpadding="0" cellspacing="0" style="font-size:12px;margin-top:10px;line-height:32px;color:#695e4a;text-align:left" width="455" class="alert_edit_info">
            <tr><td width="80">快递收货人:</td><td><input type="text" style="width:60px" name="realname" value="<?=$user['g_realname']?>" /></td></tr>
            <tr><td>身份证号:</td><td><input type="text" name="idcard" value="<?=$user['g_idcard']?>" /></td></tr>        
            <tr><td>快递收货地址:</td><td><textarea style="font-size:14px;width:350px;height:38px;" name="address"><?=$user['g_address']?></textarea> </td></tr>        
            <tr><td>邮编:</td><td><input type="text"  style="width:60px" name="zipcode" value="<?=$user['g_zipcode']?>" /></td></tr>        
            <tr><td>联系手机:</td><td><input type="text" style="width:90px" name="phone" value="<?=$user['g_phone']?>" /></td></tr>
            <tr><td>电子邮箱:</td><td><input type="text" name="mail" value="<?=$user['g_mail']?>" /></td></tr>  
            <tr><td>&nbsp;</td><td><div style="overflow:hidden;zoom:1;padding:5px 0px">
                <a class="bta4" style="margin-left:50px;" href="javascript:saveEditInfo('update_info_alert','alert_hidden_submit');">确认提交</a>
                <a class="bta4g" style="margin-right:20px"  href="javascript:showSelectKuaidi()">取消</a>
            </div>
            <div style="color:red;line-height:14px" id="alert_hidden_submit">我们会对您的信息严格保密，<br />请如实填写个人信息，以免宝贝不能准确送达</span></td></tr>        
            </table>        
            </form>
     </div>
     </div>
     <?php 
        exit();
	}
	
	function showAlertWhyNotGet($id) {
	    $id = intval($id);
	?>
	<div class="mbBig">
	<div class="mbInner">
	<div class="alerttitle">请告诉我们您未领取宝贝的原因</div>
	<form name='why_not_get_form' id="why_not_get_form" enctype="multipart/form-data" method="POST" action="">
	<input type="hidden" name="id" value="<?=$id?>" />
	<table style="text-align:left;margin-left:20px">
	<tr>
	<td width="160"><label><input type="radio" name="why_not_get" value="地区有误" />地区有误</label></td>
	<td width="160"><label><input type="radio" name="why_not_get" value="未收到短信" />未收到短信</label></td>
	</tr>
	<tr>
	<td><label><input type="radio" name="why_not_get" value="忘记领取" />忘记领取</label></td>
	<td><label><input type="radio" name="why_not_get" value="没时间领取" />没时间领取</label></td>
	</tr>
	<tr>
	<td><label><input type="radio" name="why_not_get" value="领取地址不方便" />领取地址不方便</label></td>
	<td><label><input type="radio" name="why_not_get" value="未找到柜台" />未找到柜台</label></td>
	</tr>	
	<tr>
	<td><label><input type="radio" name="why_not_get" value="不喜欢此宝贝" />不喜欢此宝贝</label></td>
	<td><label><input type="radio" name="why_not_get" value="other" />其他：</label>
	<input type="text" name="why_not_get_word" value="" style="width:100px;" />
	
	</td>
	</tr>	
	</table>
	</form>
    <div style="padding:30px 50px 0px 50px">
    <a class="bta4" style="margin-right:20px;" href="javascript:saveWhyNotGet('why_not_get_form')">确认</a>    
    <a class="bta4g" href="javascript:Mediabox.close()">取消</a>    
    </div>	
	</div>
	</div>
	<?php 
	    exit();
	}
	function saveShare() {
	    
	    $uid = intval($_SESSION['user_id']);
	    $id = intval($_POST['id']);
	    $data = $this->Luck->getShareById($id);	    
	    if (empty($uid) ||empty($data) || $data['uid']!=$uid) {
	        echo '<script>showAlert("抱歉，系统错误，请您稍后重新操作。")</script>';
	        exit();
	    }
	    $pid = $data['pid'];
	    if ($data['how_get'] == 'zhuan') {
	       $pinfo = $this->Product->getProductInfo($pid);
	    } else if ($data['how_get'] == 'huan') {
	       $pinfo = $this->Product->getChangeInfo($pid);
	    }
	    $content = $_POST['content'];
	    mb_internal_encoding('utf-8');
	    $clen = mb_strlen($content);
	    if ($clen<50 || $clen > 100) {
	        echo '<script>alert("内容长度请控制在50-100字")</script>';
	        exit();
	    }
	    if (!empty($this->params['form']['photo']['name'])) {
    	    $info = $this->params['form']['photo'];
    	    $fn = md5(time().microtime().json_encode($info));
    	    $full_fn = SystemProperties::$UPLOAD_ROOT_PATH.$fn;
    	    $target_name = $this->Upload->uploadPhoto($info, $full_fn);
    	    if ($target_name == false) {
    	        echo '<script>alert("图片上传失败，只支持jpeg,gif,jpg,png类型。")</script>';
    	        exit();
    	    }
	    } else {
	        $target_name = '';
	    }
	    $data = array('content'=>$content,'photo'=>$target_name);
	    $this->Luck->saveShare($uid, $id, $data);
	    $url = SystemProperties::$app_url.'?i='.$_SESSION['xn_user_id'].'&t='.rand(0,100000);
		      
	    $picurl = empty($target_name) ? (SystemProperties::$app_upload_img_host.$pinfo['g_img']):(SystemProperties::$UPLOAD_ROOT_PATH.$target_name);
	    $rest=new RestWrapper();

	    #$weibo = "新学期开学，天气逐渐暖和起来，在#开心赚宝# {$url} 上免费获得{$pinfo['g_name']}了,送给周末的自己！{$content}";
		#$rest->sendWeibo($weibo, $picurl);

		$weibo_msg = str_replace(array('%URL%', '%NAME%'), array($url, $pinfo['g_name']), BINGO_WEIBO);
		$weibo_msg .= $content;
		$rest->sendWeibo($weibo_msg, $picurl);

	    if (SystemProperties::$platform!='renren') {
	        echo 'parent.showAlert("提交成功！");';
	    } else {
	        echo '<script>parent.sendFeed('.json_encode($weibo).');';
	    }
	    echo 'parent.goMyluck();</script>';
        exit();
	}
	function showSaveShare($id) {
	    $uid=$_SESSION['user_id'];
	    $id = intval($id);
	    $data = $this->Luck->getShareById($id);
	    
	    if (empty($uid) ||empty($data) || $data['uid']!=$uid) {
	        echo '<script>showAlert("抱歉，系统错误，请您稍后重新操作。")</script>';
	        exit();
	    }
	 ?>
	<div class="mbBig">
    <div class="mbInner">
    	<div class="alerttitle" >提交分享</div>   
    	<form id="share_box" method="POST" target="share_callback" enctype="multipart/form-data" action="/user/saveShare" >
    	<input type="hidden" name="id" value="<?=$id?>" />
    	<table style="text-align:left;font-size:12px;line-height:35px;">
    	<tr>
    	<td width="55">宝贝照片</td>
    	<td><input type="file" name="photo"></td>
    	</tr>
    	<tr>
    	<td>分享感受</td>
    	<td><textarea name="content" style="width:350px;height:100px"></textarea></td>
    	</tr>
    	<tr>
    	<td colspan="2">图片大小不超过200k，文字至少50字，不要超过100字。<br />
    	<b style="color:#e32d0f">温馨提示：收到宝贝后，成功分享您的宝贝，将额外获得5积分奖励。</b></td>
    	</tr>	
        <td>&nbsp;</td>
    	<td>
    	<a class="bta4g fr" href="javascript:Mediabox.close()">取消</a>  
    	<a href="javascript:saveShare('share_box', 'share_callback')" class="bta4 fr">提交</a>
    	<div style="float:right;display:none"><iframe width="20" height="16" frameborder="0" scrolling="No" name="share_callback" id="share_callback"></iframe></div>
    
    	</td>
    	</tr>		
    	</table>
    	</form>
	</div>
	</div>
	
	<?php 
	    exit();
	}

}
